<template>
  <div class="app-container">
    <el-card>
      <el-tabs>
        <el-tab-pane label="角色管理">
          <el-row style="height:60px">
            <el-button type="primary" icon="el-icon-plus" size="small" @click="hAdd">新增角色</el-button>
          </el-row>
          <!-- 表格 -->
          <el-table :data="list">
            <el-table-column label="序号" width="120" type="index" />
            <el-table-column label="角色名称" width="240" prop="name" />
            <el-table-column label="描述" prop="description" />
            <el-table-column label="操作">
              <template #default="{row}">
                <el-button size="small" type="success" @click="hPer(row.id)">分配权限</el-button>
                <el-button size="small" type="primary" @click.native="hEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click.native="hDel(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <el-row type="flex" justify="center" align="middle" style="height: 60px">
            <!-- 分页组件 -->
            <el-pagination
              :current-page="params.page"
              :page-sizes="[2, 3, 5, 8,10]"
              :page-size="params.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <!-- 新增/修改角色 -->
      <el-dialog
        :title="isEdit?'编辑角色':'新增角色'"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hClose"
      >
        <el-form
          ref="formRef"
          :model="form"
          label-width="100px"
          :rules="rules"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" />
          </el-form-item>
        </el-form>
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="dialogFormVisible=false">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>

      <!-- 分配权限 -->
      <el-dialog title="分配权限" :visible.sync="dialogShowtree">
        <assignPer
          :id="roleId"
          ref="assignPer"
          @success="hSuccess"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import assignPer from './assignPermission.vue'
import { addRoles, delRolesById, editRolesById, getRoles } from '@/api/settings'
export default {
  components: {
    assignPer
  },
  data() {
    return {
      list: [],
      total: 0,
      params: {
        pagesize: 2,
        page: 1
      },
      dialogFormVisible: false,
      form: {
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      isEdit: false,
      dialogShowtree: false,
      roleId: ''
    }
  },
  created() {
    this.locagetRoles()
  },
  methods: {
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.params.pagesize = val
      this.locagetRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.params.page = val
      this.locagetRoles()
    },
    async locagetRoles() {
      const res = await getRoles(this.params)
      this.list = res.data.data.rows
      this.total = res.data.data.total
    },
    // 提交
    hSubmit() {
      this.$refs.formRef.validate(valid => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 添加
    async doAdd() {
      try {
        const res = await addRoles(this.form)
        console.log(res)
        this.dialogFormVisible = false
        this.total++
        const maxPage = Math.ceil(this.total / this.params.pagesize)
        this.params.page = maxPage
        this.locagetRoles()
      } catch (error) {
        console.log(error)
      }
    },
    hAdd() {
      this.dialogFormVisible = true
      this.isEdit = false
    },
    // 修改
    async doEdit() {
      try {
        const res = await editRolesById(this.form)
        console.log('更新角色详情', res)
        this.dialogFormVisible = false
        this.locagetRoles()
      } catch (error) {
        console.log(error)
      }
    },
    async hEdit(row) {
      this.dialogFormVisible = true
      this.isEdit = true
      console.log(row)
      // 数据回显
      this.form = { ...row }
    },
    // 分配权限
    hPer(id) {
      this.dialogShowtree = true
      this.roleId = id
      this.$nextTick(() => {
        this.$refs.assignPer.loadPermissionList()
      })
    },
    hSuccess() {
      this.perShowDialog = false
      this.$refs.assignPer.resetChecked()
    },
    // 取消
    hClose() {
      this.$refs.formRef.resetFields()
      this.form = {
        name: '',
        description: ''
      }
    },
    // 删除
    async hDel(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await delRolesById(row.id)
        console.log(res)
        if (this.list.length === 1) { // 当删除的是本页最后一个数据
          this.params.page-- // this.locagetRoles() 不会更新呢params.page 需要手动修改
        } if (this.params.page <= 0) { // 没有数据了就显示一页码
          this.params.page = 1
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.locagetRoles()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>
